/*
 * File:   newsimpletest.c
 * Author: Fcten
 *
 * Created on 2015-5-6, 12:33:31
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

#include "../libjson.h"

static long _GetFileSize(char *filename)
{
	struct stat stat_buf;
	int ret;

	ret=stat(filename,&stat_buf);
	
	if( ret == -1 )
		return -1;
	
	return stat_buf.st_size;
}

static int ReadEntireFile( char *filename , char *mode , char *buf , long *bufsize )
{
	FILE	*fp = NULL ;
	long	filesize ;
	long	lret ;
	
	if( filename == NULL )
		return -1;
	if( strcmp( filename , "" ) == 0 )
		return -1;
	
	filesize = _GetFileSize( filename ) ;
	if( filesize  < 0 )
		return -2;
	
	fp = fopen( filename , mode ) ;
	if( fp == NULL )
		return -3;
	
	if( filesize <= (*bufsize) )
	{
		lret = fread( buf , sizeof(char) , filesize , fp ) ;
		if( lret < filesize )
		{
			fclose( fp );
			return -4;
		}
		
		(*bufsize) = filesize ;
		
		fclose( fp );
		
		return 0;
	}
	else
	{
		lret = fread( buf , sizeof(char) , (*bufsize) , fp ) ;
		if( lret < (*bufsize) )
		{
			fclose( fp );
			return -4;
		}
		
		fclose( fp );
		
		return 1;
	}
}

static int ReadEntireFileSafely( char *filename , char *mode , char **pbuf , long *pbufsize )
{
	long	filesize ;
	
	int	nret ;
	
	filesize = _GetFileSize( filename );
	
	(*pbuf) = (char*)malloc( filesize + 1 ) ;
	if( (*pbuf) == NULL )
		return -1;
	memset( (*pbuf) , 0x00 , filesize + 1 );
	
	nret = ReadEntireFile( filename , mode , (*pbuf) , & filesize ) ;
	if( nret )
	{
		free( (*pbuf) );
		(*pbuf) = NULL ;
		return nret;
	}
	else
	{
		if( pbufsize )
			(*pbufsize) = filesize ;
		return 0;
	}
}

void cb( json_task_t * task, json_object_t * node ) {
    json_object_t * parent = node;
    while( parent ) {
        if( parent->key ) {
            printf("%.*s/", (int)parent->key_len, parent->key);
        } else {
            printf("%d/", (int)parent->key_len);
        }
        parent = parent->next;
    }
    printf(" : ");
    json_print_value(node);
    printf("\n");
}

int main( int argc , char *argv[] ) {
    json_task_t t;
    int nret = 0;
    char *json_buffer = NULL;

    //if( argc != 4 ) return 1;
    
    nret = ReadEntireFileSafely( "./tests/test.json" , "rb" , &json_buffer , NULL ) ;
    if( nret )
    {
        printf( "ReadEntireFileSafely[%s] failed[%d]\n" , argv[1] , nret );
        return nret;
    }
    
    t.str = json_buffer;
    t.len = strlen(json_buffer);
    if( 0 ) {
        t.callback = cb;
    } else {
        t.callback = NULL;
    }

    int l,r,i;
    if( json_parser(&t) == 0 ) {
        if( t.callback == NULL ) {
            json_print(t.root);
        }
        
        printf("%s\n",t.err_msg);

        for( i = 1 ; i > 1 ; i -- ) {
            json_parser(&t);
        }
    } else {
        json_err_psotion(&t, &l, &r);
        printf("line: %d, row %d: %s\n", l, r, t.err_msg);
    }
    
    return 0;
}
